<script setup lang="ts">
// /api/admin/profits/service-types/ranking
// 定义组件名
defineOptions({ name: "ServiceProfitRankingChart" });

import { useDark, useECharts } from "@pureadmin/utils";
import { ref, watch, nextTick, computed, type PropType } from "vue";
import { generatePalette } from "@/plugins/echarts";

// TS 类型定义
interface RankingItem {
  serviceType: string;
  cost: number;
  rank: number;
  profit: number;
  sales: number;
  tasks: number;
}

// 组件接收的数据对象（data 对象），其中 ranking 为关键数据数组
const props = defineProps({
  data: {
    type: Array as PropType<RankingItem[]>,
    default: () => []
  }
});

// ECharts 初始化
const chartRef = ref<HTMLDivElement>();
const { isDark } = useDark();
const themeName = "lowSaturationFancy";
const { setOptions } = useECharts(chartRef, { theme: themeName });

// 排序并提取用于图表的分类与数值
const sorted = computed(() =>
  props.data.slice().sort((a, b) => a.rank - b.rank)
);
const categories = computed(() =>
  sorted.value.map(item => `${item.rank}. ${item.serviceType}`)
);
const values = computed(() => sorted.value.map(item => item.profit));

// 监听数据变化，渲染图表
watch(
  () => props.data,
  async list => {
    await nextTick();

    const names = categories.value;
    const dataValues = values.value;
    const colors = generatePalette(dataValues.length);

    // 水平柱状图配置
    const barOption = {
      color: colors,
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" }
      },
      grid: {
        left: "120px",
        right: "20px",
        top: "20px",
        bottom: "20px",
        containLabel: true
      },
      xAxis: {
        type: "value",
        axisLabel: { color: isDark.value ? "#fff" : "#666" },
        splitLine: { show: false }
      },
      yAxis: {
        type: "category",
        data: names,
        inverse: true,
        axisLabel: { color: isDark.value ? "#fff" : "#666" }
      },
      series: [
        {
          name: "Profit",
          type: "bar",
          barWidth: 20,
          itemStyle: { borderRadius: [0, 10, 10, 0] },
          label: { show: true, position: "insideRight", formatter: "{c}" },
          data: dataValues
        }
      ]
    };

    // 漏斗图配置（可选，强调排名层级）
    const funnelOption = {
      color: colors,
      tooltip: { trigger: "item", formatter: "{b}: {c}" },
      series: [
        {
          name: "Ranking",
          type: "funnel",
          left: "10%",
          top: "10%",
          bottom: "10%",
          width: "80%",
          minSize: "10%",
          maxSize: "100%",
          sort: "descending",
          gap: 2,
          label: {
            show: true,
            position: "inside",
            color: "#fff",
            formatter: "{b}\n{c}"
          },
          labelLine: { length: 6 },
          data: sorted.value.map(item => ({
            value: item.profit,
            name: item.serviceType
          }))
        }
      ]
    };

    // 默认渲染柱状图，若需漏斗图可切换到 funnelOption
    // setOptions(barOption);
    setOptions(funnelOption);
  },
  { immediate: true, deep: true }
);
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 365px" />
</template>
